package com.r2coding.auth.web.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.arronlong.httpclientutil.HttpClientUtil;
import com.arronlong.httpclientutil.common.HttpConfig;
import com.arronlong.httpclientutil.common.HttpHeader;
import com.arronlong.httpclientutil.exception.HttpProcessException;
import com.r2coding.auth.web.util.Result;
import com.r2coding.auth.web.util.ResultEnum;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author:98k灬
 * @since:2022/04/09 21:35
 **/
@Service
public class AuthService {
    @Autowired
    LoadBalancerClient loadBalancerClient;

    // 刷新令牌
    public Result refreshToken(String header, String refreshToken) throws HttpProcessException {
        ServiceInstance instance = loadBalancerClient.choose("blog-auth");
        if (instance == null) {
            return Result.error("未找到有效认证服务器");
        }
        // String refreshTokenUrl = instance.getUri().toString() + "/auth/oauth/token";
        String refreshTokenUrl = instance.getUri().toString() + "/oauth/token";
        Map<String, Object> map = new HashMap<>();
        map.put("grant_type", "refresh_token");
        map.put("refresh_token", refreshToken);
        Header[] headers = HttpHeader.custom()
                .contentType(HttpHeader.Headers.APP_FORM_URLENCODED)
                .authorization(header)
                .build();
        HttpConfig config = HttpConfig.custom().headers(headers).url(refreshTokenUrl).map(map);
        String token = HttpClientUtil.post(config);
        JSONObject jsonObject = (JSONObject) JSON.parse(token);
        if (StringUtils.isNotEmpty(jsonObject.getString("error"))) {
            return Result.build(ResultEnum.TOKEN_PAST);
        }
        return Result.ok(jsonObject);
    }
}
